<!-- build time:Tue Dec 17 2019 19:26:50 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Spring,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="从Spring3.0开始，Spring可以通过注解的方式来配置Bean。这里先介绍以传统的XML配置式来配置Bean。用一场选秀比赛来模拟Spring装备Bean过程。一场比赛中，需要一些参赛者来参加比赛，为此我们定义一个Performer接口：123public interface Performer &amp;#123;    public void perform();&amp;#125;"><meta name="keywords" content="Spring"><meta property="og:type" content="article"><meta property="og:title" content="Spring 构造器注入"><meta property="og:url" content="http://mrbird.cc/Spring-构造器注入.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="从Spring3.0开始，Spring可以通过注解的方式来配置Bean。这里先介绍以传统的XML配置式来配置Bean。用一场选秀比赛来模拟Spring装备Bean过程。一场比赛中，需要一些参赛者来参加比赛，为此我们定义一个Performer接口：123public interface Performer &amp;#123;    public void perform();&amp;#125;"><meta property="og:locale" content="zh-Hans"><meta property="og:updated_time" content="2019-10-28T12:14:46.287Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Spring 构造器注入"><meta name="twitter:description" content="从Spring3.0开始，Spring可以通过注解的方式来配置Bean。这里先介绍以传统的XML配置式来配置Bean。用一场选秀比赛来模拟Spring装备Bean过程。一场比赛中，需要一些参赛者来参加比赛，为此我们定义一个Performer接口：123public interface Performer &amp;#123;    public void perform();&amp;#125;"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>Spring 构造器注入 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Spring-构造器注入.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Spring 构造器注入</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-09-24T09:30:46+08:00">2016-09-24 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>从Spring3.0开始，Spring可以通过注解的方式来配置Bean。这里先介绍以传统的XML配置式来配置Bean。</p><p>用一场选秀比赛来模拟Spring装备Bean过程。</p><p>一场比赛中，需要一些参赛者来参加比赛，为此我们定义一个Performer接口：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Performer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">perform</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><a id="more"></a><p>参赛选手都实现了这个Performer接口。</p><p>以下为一个典型的Spring XML配置文件(Spring容器，Spring上下文)：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:util</span>=<span class="string">"http://www.springframework.org/schema/util"</span>  </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:tx</span>=<span class="string">"http://www.springframework.org/schema/tx"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:jpa</span>=<span class="string">"http://www.springframework.org/schema/data/jpa"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:mvc</span>=<span class="string">"http://www.springframework.org/schema/mvc"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xsi:schemaLocation</span>=<span class="string">"</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/context/spring-context-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/util</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/util/spring-util-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/jee</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/jee/spring-jee-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/tx</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/data/jpa</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--Bean declarations go here --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>在<code>&lt;beans&gt;</code>元素内，我们可以配置所有Spring配置信息以及<code>&lt;bean&gt;</code>元素的声明。除此之外，Spring还自带了包括<code>&lt;beans&gt;</code>在内的10大命名空间：</p><table><tr><th>命名空间</th><th>用途</th></tr><tr><td>aop</td><td>为声明切面以及将@AspectJ注解的类代理为Spring切面提供了配置元素</td></tr><tr><td>beans&nbsp;&nbsp;&nbsp;&nbsp;</td><td>支持声明Bean和装配Bean，是Spring最核心也是最原始的命名空间</td></tr><tr><td>context</td><td><p>为配置Spring应用上下文提供了配置元素，包括自动检测和自动装配Bean，注入非Spring直</p><p>接管理的对象</p></td></tr><tr><td>jee&nbsp;&nbsp;&nbsp;&nbsp;</td><td>提供了与Java EE API的集成，例如JNDI和EJB</td></tr><tr><td>jms</td><td>为声明消息驱动的POJO提供了配置元素</td></tr><tr><td>lang</td><td>支持配置由Groovy，JRuby或BeanShell等脚本实现的Bean</td></tr><tr><td>mvc</td><td>启动Spring MVC的能力，例如面向注解的控制器，视图控制器和拦截器</td></tr><tr><td>oxm</td><td>支持Spring的对象到XML映射配置</td></tr><tr><td>tx</td><td>提供声明事务配置</td></tr><tr><td>util</td><td>提供各种各样的工具类元素，包括把集合配置为Bean，支持属性占位符元素</td></tr></table><p>回归比赛，第一位参赛者是一个Juggler(杂技师)，声明一个Juggler Bean：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Juggler</span> <span class="keyword">implements</span> <span class="title">Performer</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> beanBags=<span class="number">3</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Juggler</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Juggler</span><span class="params">(<span class="keyword">int</span> beanBags)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.beanBags = beanBags;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">perform</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"throws "</span>+beanBags+<span class="string">" beanBags"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>Juggler实现了Performer接口，默认可以同时抛出三个豆袋子。也可以通过有参构造器改变袋子数量。</p><p>现在有请第一位叫duke的杂技师上场！在applicationContext.xml文件中配置Duke：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"duke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Juggler"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>id表明他叫duke，class表明他是一个juggler。现在让duke上台表演：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Show</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        String conf=<span class="string">"applicationContext.xml"</span>;</span><br><span class="line">        ApplicationContext ac=<span class="keyword">new</span> ClassPathXmlApplicationContext(conf);</span><br><span class="line">        Juggler duke=(Juggler)ac.getBean(<span class="string">"duke"</span>);</span><br><span class="line">        duke.perform(); <span class="comment">//扔了 3 个豆袋子</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="构造器注入"><a href="#构造器注入" class="headerlink" title="构造器注入"></a>构造器注入</h2><p>评委觉得这并没有什么难度，于是duke决定一次性扔15个豆袋子！修改duke<code>&lt;bean&gt;</code>的配置：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"duke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Juggler"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"15"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>也可以使用<code>c-</code>命名空间代替<code>&lt;constructor-arg&gt;</code>标签，要使用它的话，现在XML顶部声明其模式：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xmlns:c="http://www.springframework.org/schema/c"</span><br></pre></td></tr></table></figure><p></p><p>上面的配置可以改为：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"duke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Juggler"</span> <span class="attr">c:beanBags</span>=<span class="string">"15"</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>或者：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"duke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Juggler"</span> <span class="attr">c:_0</span>=<span class="string">"15"</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>像这种只有一个参数的话也可以写为：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"duke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Juggler"</span> <span class="attr">c:_</span>=<span class="string">"15"</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>Juggler类有两个构造器，无参和有参。当没有声明<code>&lt;constructor-arg&gt;</code>的时候，Spring将默认使用无参的构造方法。现在，我们将<code>&lt;constructor-arg&gt;</code>的value设置位15的时候，Spring使用有参构造方法来改变属性beanBags的值。</p><p>再次表演，输出：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">扔了 15 个豆袋子</span><br><span class="line">掌声雷动。</span><br></pre></td></tr></table></figure><p></p><p>稍等！duke说他还会边扔袋子变朗诵诗歌！为此我们定义一个PoeticJuggler（会朗诵的杂技师）：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PoeticJuggler</span> <span class="keyword">extends</span> <span class="title">Juggler</span></span>&#123;</span><br><span class="line">    <span class="comment">//诗歌属性</span></span><br><span class="line">    <span class="keyword">private</span> Poem poem;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PoeticJuggler</span><span class="params">(Poem poem)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.poem = poem;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PoeticJuggler</span><span class="params">(<span class="keyword">int</span> beanBags,Poem poem)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//继承豆袋子属性</span></span><br><span class="line">        <span class="keyword">super</span>(beanBags);</span><br><span class="line">        <span class="keyword">this</span>.poem = poem;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">perform</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//继承扔袋子技能</span></span><br><span class="line">        <span class="keyword">super</span>.perform();</span><br><span class="line">        System.out.println(<span class="string">"边朗诵..."</span>);</span><br><span class="line">        <span class="comment">//朗诵诗歌</span></span><br><span class="line">        poem.recite();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>诗歌接口：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Poem</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">recite</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>duke最喜欢的是普希金的《假如生活欺骗了你》，为此我们定义一个DeceivedByLife类，实现Poem接口：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DeceivedByLife</span> <span class="keyword">implements</span> <span class="title">Poem</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String[] LINES = &#123;</span><br><span class="line">        <span class="string">"假如生活欺骗了你，"</span>,</span><br><span class="line">        <span class="string">"不要悲伤，不要心急！"</span>,</span><br><span class="line">        <span class="string">"忧郁的日子里须要镇静："</span>,</span><br><span class="line">        <span class="string">"相信吧，快乐的日子将会来临！"</span>,</span><br><span class="line">        <span class="string">"心儿永远向往着未来；"</span>,</span><br><span class="line">        <span class="string">"现在却常是忧郁。"</span>,</span><br><span class="line">        <span class="string">"一切都是瞬息，一切都将会过去；"</span>,</span><br><span class="line">        <span class="string">"而那过去了的，就会成为亲切的怀恋"</span>&#125;;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DeceivedByLife</span><span class="params">()</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//朗诵诗歌</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">recite</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;LINES.length;i++)&#123;</span><br><span class="line">            System.out.println(LINES[i]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在Spring容器里配置这首诗歌：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"deceivedByLife"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.DeceivedByLife"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>现在duke是一个poeticJuggler了，为此我们修改duke的<code>&lt;bean&gt;</code>配置：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"poeticDuke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.PoeticJuggler"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"15"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"deceivedByLife"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p><code>c-</code>命名空间写法：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"poeticDuke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.PoeticJuggler"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">c:_beanBags</span>=<span class="string">"15"</span> </span></span><br><span class="line"><span class="tag">    <span class="attr">c:_poem-ref</span>=<span class="string">"deceivedByLife"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>或者：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"poeticDuke"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.PoeticJuggler"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">c:_0</span>=<span class="string">"15"</span> </span></span><br><span class="line"><span class="tag">    <span class="attr">c:_1-ref</span>=<span class="string">"deceivedByLife"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>当Spring碰到deceivedByLife和poeticDuke的<code>&lt;bean&gt;</code>声明时，它所执行的逻辑本质和下面的Java代码是一样的：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Poem deceivedByLife = <span class="keyword">new</span> DeceivedByLife();</span><br><span class="line">Performer duke = <span class="keyword">new</span> PoeticJuggler(<span class="number">15</span>,deceivedByLife);</span><br></pre></td></tr></table></figure><p></p><p>现在，duke再次进行了表演：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Show</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        String conf=<span class="string">"applicationContext.xml"</span>;</span><br><span class="line">        ApplicationContext ac=<span class="keyword">new</span> ClassPathXmlApplicationContext(conf);</span><br><span class="line">        Juggler duke=(PoeticJuggler)ac.getBean(<span class="string">"poeticDuke"</span>);</span><br><span class="line">        duke.perform();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>输出：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">扔了 15 个豆袋子</span><br><span class="line">边朗诵...</span><br><span class="line">假如生活欺骗了你，</span><br><span class="line">不要悲伤，不要心急！</span><br><span class="line">忧郁的日子里须要镇静：</span><br><span class="line">相信吧，快乐的日子将会来临！</span><br><span class="line">心儿永远向往着未来；</span><br><span class="line">现在却常是忧郁。</span><br><span class="line">一切都是瞬息，一切都将会过去；</span><br><span class="line">而那过去了的，就会成为亲切的怀恋</span><br></pre></td></tr></table></figure><p></p><p>掌声再次雷动。</p><h2 id="通过工厂方法创建Bean"><a href="#通过工厂方法创建Bean" class="headerlink" title="通过工厂方法创建Bean"></a>通过工厂方法创建Bean</h2><p>有时候，一个类没有公开的构造方法，这时候就不能使用构造器注入了。Spring支持<code>&lt;bean&gt;</code>元素的<code>factory-method</code>方法来装配Bean。</p><p>创建一个舞台类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Stage</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Stage</span><span class="params">()</span></span>&#123;</span><br><span class="line">    	</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//延迟加载实例</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">stageSingletonHolder</span></span>&#123;</span><br><span class="line">        <span class="keyword">static</span> Stage instance=<span class="keyword">new</span> Stage();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//返回实例</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Stage <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stageSingletonHolder.instance;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createStage</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"创造一个舞台"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>Stage作为一个单例类，没有公开的构造方法，相反，静态方法<code>getInstance()</code>每次调用都返回一个相同的Stage实例。</p><p><code>&lt;bean&gt;</code>元素的<code>factory-method</code>属性允许我们调用一个静态方法，从而代替构造方法来创建一个类的实例。</p><p>在Spring上下文中配置Stage<code>&lt;bean&gt;</code>：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"stage"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Stage"</span> <span class="attr">factory-method</span>=<span class="string">"getInstance"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>现在从Spring容器中获取这个<code>&lt;bean&gt;</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CreateStage</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        String conf=<span class="string">"applicationContext.xml"</span>;</span><br><span class="line">        ApplicationContext ac=<span class="keyword">new</span> ClassPathXmlApplicationContext(conf);</span><br><span class="line">        Stage stage=(Stage)ac.getBean(<span class="string">"stage"</span>);</span><br><span class="line">        stage.createStage();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>输出：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">创造一个舞台</span><br></pre></td></tr></table></figure><p></p><h2 id="Bean作用域"><a href="#Bean作用域" class="headerlink" title="Bean作用域"></a>Bean作用域</h2><p>所有Spring Bean默认都是单例的。如果现在要创建一个”门票”类，每个人的门票肯定是不一样的。为了让Spring每次请求都产生一个新的实例，我们可以定义如下ticket<code>&lt;bean&gt;</code>：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"ticket"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Ticket"</span> <span class="attr">scope</span>=<span class="string">"prototype"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>除了prototype，Spring还提供了其他几个作用域选项：</p><table><tr><th>作用域</th><th>定义</th></tr><tr><td>singleton</td><td>在每一个spring容器中，一个Bean定义只有一个对象实例（默认）</td></tr><tr><td>prototype</td><td>允许Bean的定义可以被实例化任意次（每次调用都创建一个新的实例）</td></tr><tr><td>request</td><td>在一次HTTP请求中，每个Bean定义对应一个实例。该作用域仅在基于Web的Spring上下文中才有效</td></tr><tr><td>session</td><td>在一个HTTP Session中，每个Bean定义对应一个实例。该作用域仅在基于Web的Spring上下文中才有效</td></tr><tr><td>global-session</td><td>在一个全局HTTP Session中，每个Bean定义对应一个实例。该作用域仅在Protlet上下文中才有效</td></tr></table><p>Spring的单例Bean只能保证在每个应用上下文中只有一个Bean实例。没有人能够阻止你使用传统的方式实例化同一个Bean，或者你甚至可以定义几个<bean>声明来实例化同一个Bean。</bean></p><h2 id="初始化和销毁Bean"><a href="#初始化和销毁Bean" class="headerlink" title="初始化和销毁Bean"></a>初始化和销毁Bean</h2><p>为Bean定义初始化和销毁操作，只需要使用<code>init-method</code>和<code>destroy-method</code>参数来配置<code>&lt;bean&gt;</code>元素。init-method属性指定了在初始化Bean时要调用的方法。destroy-method属性指定了Bean从容器移除之前要调用的方法。</p><p>现在定义一个灯光类Light：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Light</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">turnOnTheLight</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"开灯"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">turnOffTheLight</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"关灯"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在容器中配置该Bean：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"light"</span> <span class="attr">class</span>=<span class="string">"com.spring.entity.Light"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">init-method</span>=<span class="string">"turnOnTheLight"</span> <span class="attr">destroy-method</span>=<span class="string">"turnOffTheLight"</span>/&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>加载容器，以此来实例化light：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LightControl</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        String conf=<span class="string">"applicationContext.xml"</span>;</span><br><span class="line">        <span class="comment">//加载容器</span></span><br><span class="line">        ApplicationContext ac=<span class="keyword">new</span> ClassPathXmlApplicationContext(conf);</span><br><span class="line">        <span class="comment">//关闭容器</span></span><br><span class="line">        ((ClassPathXmlApplicationContext)ac).close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>输出：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">开灯</span><br><span class="line">...</span><br><span class="line">关灯</span><br></pre></td></tr></table></figure><p></p><p>我们还可以定义默认的init-method和destroy-method。如果上下文中Bean定义了名字相同的初始化和销毁方法，我们可以统一配置default-init-method和default-destroy-method：</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:util</span>=<span class="string">"http://www.springframework.org/schema/util"</span>  </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:tx</span>=<span class="string">"http://www.springframework.org/schema/tx"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:jpa</span>=<span class="string">"http://www.springframework.org/schema/data/jpa"</span> </span></span><br><span class="line"><span class="tag">	<span class="attr">xmlns:mvc</span>=<span class="string">"http://www.springframework.org/schema/mvc"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xsi:schemaLocation</span>=<span class="string">"</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/context/spring-context-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/util</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/util/spring-util-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/jee</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/jee/spring-jee-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/tx</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/data/jpa</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="tag"><span class="string">    	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">default-init-method</span>=<span class="string">"turnOnTheLight"</span> </span></span><br><span class="line"><span class="tag">        <span class="attr">default-destroy-method</span>=<span class="string">"turnOffTheLight"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--Bean declarations go here --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>为Bean定义初始化和销毁的方法是让Bean实现Spring的InitializingBean和DisposableBean接口。InitializingBean声明了一个afterPropertiesSet()方法作为初始化方法。DisposableBean声明了一个destroy()方法作为销毁方法。在Spring容器中无需任何配置。</p><p>修改Light类：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Light</span> <span class="keyword">implements</span> <span class="title">InitializingBean</span>,<span class="title">DisposableBean</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"开灯"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"关灯"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;﻿​</span><br></pre></td></tr></table></figure><p></p><div class="note danger"><p>这种方法的缺点显而易见了：实现Spring的接口意味着Bean与Spring的API产生了耦合。所以这种方法并不推荐！</p></div><blockquote><p><a href="https://book.douban.com/subject/5283241/" target="_blank" rel="noopener">《Spring In Action》</a>读书笔记</p></blockquote><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Spring-构造器注入.html" title="Spring 构造器注入">http://mrbird.cc/Spring-构造器注入.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Spring/" rel="tag"># Spring</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/jQuery选择器总结.html" rel="next" title="jQuery选择器总结"><i class="fa fa-chevron-left"></i> jQuery选择器总结</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Spring-Setter方法注入.html" rel="prev" title="Spring Setter方法注入">Spring Setter方法注入 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#构造器注入"><span class="nav-number">1.</span> <span class="nav-text">构造器注入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过工厂方法创建Bean"><span class="nav-number">2.</span> <span class="nav-text">通过工厂方法创建Bean</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Bean作用域"><span class="nav-number">3.</span> <span class="nav-text">Bean作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初始化和销毁Bean"><span class="nav-number">4.</span> <span class="nav-text">初始化和销毁Bean</span></a></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->